﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using CE.User;
using CE.HomeLoan;
using CE.Global;
using CE.Database;

public partial class home_loan_home_loan : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {

            Uri myUri = new Uri(HttpContext.Current.Request.Url.ToString());

            string domainUrl = "http://" + myUri.Host;
            string _link = domainUrl + "/home-loan/mortgage-calculator.aspx";

            //hplkMcal.NavigateUrl = _link;

            //int _startYear = 5;
            //int _endYear = 30;
            //for (int i = _startYear; i <= _endYear; i++)
            //{
            //    ddlLoanTenure.Items.Add(new ListItem(i.ToString(), i.ToString()));
            //}
            //ddlLoanTenure.Items.Insert(0, new ListItem("Select", "-1"));


            //ddlLoanTenure.Attributes.Add("onblur", "ShowValidationEffect('" + ddlLoanTenure.ClientID + "','" + rfvLoanTenure.ClientID + "');");
            //ddlRate.Attributes.Add("onblur", "ShowValidationEffect('" + ddlRate.ClientID + "','" + rfvRate.ClientID + "');");

            ddlMortgageType.Attributes.Add("onblur", "ShowValidationEffect('" + ddlMortgageType.ClientID + "','" + rfvMortgageType.ClientID + "');");
            ddlPropertyType.Attributes.Add("onblur", "ShowValidationEffect('" + ddlPropertyType.ClientID + "','" + rfvPropertyType.ClientID + "');");
            //ddlProperty.Attributes.Add("onblur", "ShowValidationEffect('" + ddlProperty.ClientID + "','" + rfvProperty.ClientID + "');");
            txtLoanAmount.Attributes.Add("onblur", "formatThousandNumber(this.value);ShowValidationEffectTwo('" + txtLoanAmount.ClientID + "','" + rfvLoanAmount.ClientID + "','" + revLoanAmount.ClientID + "');");
            //txtPropertyValue.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtPropertyValue.ClientID + "','" + rfvPropertyValue.ClientID + "','" + revPropertyValue.ClientID + "');");

            txtCalLoanAmount.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtCalLoanAmount.ClientID + "','" + rfvCalLoanAmount.ClientID + "','" + revCalLoanAmount.ClientID + "');");
            txtCalIntrestRate.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtCalIntrestRate.ClientID + "','" + rfvCalIntrestRate.ClientID + "','" + revCalIntrestRate.ClientID + "');");
            txtCalLoanTenure.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtCalLoanTenure.ClientID + "','" + rfvCalLoanTenure.ClientID + "','" + revCalLoanTenure.ClientID + "');");

            //Session[General.HFId] = null;
            GetCurrentBankList();

            ShowDetails();
            General.ClearAllSession(this.Page, "HL");
            Session[General.ViewedDetailsId] = LogUserViewedHistory().ToString();

            //if (rdoYesOffsetSchemes.Checked || rdoNoOffsetSchemes.Checked) txtOffsetSchemes.Text = "1";
            //if (rdoYesLockin.Checked || rdoNoLockin.Checked) txtLockin.Text = "1";

        }
    }

    private void ShowDetails()
    {
        if (Session[General.HLId] != null)
        {
            HomeLoan _homeloan = new HomeLoan();
            HomeLoanDB _homeloandb = new HomeLoanDB();
            _homeloan = _homeloandb.GetHomeLoan(Convert.ToInt64(Session[General.HLId].ToString()));
            if (_homeloan != null)
            {
                ddlMortgageType.Text = _homeloan.HLMortgageType.ToString();
                ddlPropertyType.Text = _homeloan.HLPropertyType.ToString();
                //ddlProperty.Text = _homeloan.HLProperty.ToString();
                txtLoanAmount.Text = _homeloan.HLAmount.ToString();
                //ddlLoanTenure.Text = _homeloan.HLLoanTenure.ToString();
                txtLoanTenure.Text = _homeloan.HLLoanTenure.ToString();
                lblLoanAmountDisplay.Text = "$S " + _homeloan.HLAmount.ToString("#,000");
                ddlYourCurrentBank.Text = _homeloan.Info1;
                //ddlRate.Text = _homeloan.HLInterestRate.ToString();
                //rdoYesLockin.Checked = _homeloan.HLLockIn;
                //rdoNoLockin.Checked = !_homeloan.HLLockIn;
                //rdoYesOffsetSchemes.Checked = _homeloan.HLOffsetSchemes;
                //rdoNoOffsetSchemes.Checked = !_homeloan.HLOffsetSchemes;
            }
        }
    }
    protected void ibtNext(object sender, EventArgs e)
    {
        ChangeValidationEffectServerSide("homeloan");
        if (Page.IsValid)
        {
            Int64 _result = 0;
            HomeLoan _homeloan = new HomeLoan();
            HomeLoanDB _homeloandb = new HomeLoanDB();
            if (Session[General.HLId] != null)
            {
                _homeloan = _homeloandb.GetHomeLoan(Convert.ToInt64(Session[General.HLId].ToString()));
            }
            else
            {
                _homeloan.HLId = 0;
            }
            //_homeloan.HLId = 0;
            _homeloan.StepId = 1;
            _homeloan.HLMortgageType = Convert.ToInt16(ddlMortgageType.Text);
            _homeloan.HLPropertyType = Convert.ToInt16(ddlPropertyType.Text);
            //_homeloan.HLProperty = Convert.ToInt16(ddlProperty.Text);
            _homeloan.HLAmount = Convert.ToSingle(txtLoanAmount.Text);
            _homeloan.HLPropertyValue = 0;// Convert.ToSingle(txtPropertyValue.Text);
            //_homeloan.HLLoanTenure = Convert.ToInt16(ddlLoanTenure.Text);
            _homeloan.HLLoanTenure = Convert.ToInt16(txtLoanTenure.Text);
            //_homeloan.HLInterestRate = Convert.ToInt16(ddlRate.Text);
            //_homeloan.HLOffsetSchemes = rdoYesOffsetSchemes.Checked;
            //_homeloan.HLLockIn = rdoYesLockin.Checked;
            if (ddlMortgageType.Text == "1")
            {
                _homeloan.Info1 = ddlYourCurrentBank.Text;
            }
            else
            {
                _homeloan.Info1 = "-1";
            }
            _homeloan.NInfo1 = 0;
            _homeloan.NInfo2 = 0;
            _homeloan.NInfo3 = 0;
            _homeloan.NInfo4 = 0;
            if (Session[General.UserId] != null)
            {
                _homeloan.RefCEUserId = Convert.ToInt64(Session[General.UserId].ToString());
            }
            else
            {
                _homeloan.RefCEUserId = 0;
            }
            if (Session[General.UserId] != null)
            {
                _homeloan.ViewedDetailId = Convert.ToInt64(Session[General.ViewedDetailsId].ToString());
            }
            else
            {
                _homeloan.ViewedDetailId = 0;
            }
            _homeloan.Status = false;
            _result = _homeloandb.Insert(_homeloan);
            if (_result > 0)
            {
                Session[General.HLId] = _result;
                Response.Redirect("results.aspx");
            }
        }
    }

    private void ChangeValidationEffectServerSide(string strValidationGroup)
    {
        //Loan Purpose
        if (rfvMortgageType.Enabled && rfvMortgageType.ValidationGroup == strValidationGroup)
        {
            rfvMortgageType.Validate();
            if (rfvMortgageType.IsValid == false)
            {
                ddlMortgageType.ControlStyle.CssClass = "validationError";
            }
            else
            {
                ddlMortgageType.ControlStyle.CssClass = "";
            }
        }
        else
        {
            ddlMortgageType.ControlStyle.CssClass = "";
        }


        //Your Current Bank
        if (ddlMortgageType.Text == "1")
        {
            rfvYourCurrentBank.Enabled = true;
        }
        else
        {
            rfvYourCurrentBank.Enabled = false;
        }

        if (rfvYourCurrentBank.Enabled && rfvYourCurrentBank.ValidationGroup == strValidationGroup)
        {
            rfvYourCurrentBank.Validate();
            if (rfvYourCurrentBank.IsValid == false)
            {
                ddlYourCurrentBank.ControlStyle.CssClass = "validationError";
            }
            else
            {
                ddlYourCurrentBank.ControlStyle.CssClass = "";
            }
        }
        else
        {
            ddlYourCurrentBank.ControlStyle.CssClass = "";
        }


        //Property Type
        if (rfvPropertyType.Enabled && rfvPropertyType.ValidationGroup == strValidationGroup)
        {
            rfvPropertyType.Validate();
            if (rfvPropertyType.IsValid == false)
            {
                ddlPropertyType.ControlStyle.CssClass = "validationError";
            }
            else
            {
                ddlPropertyType.ControlStyle.CssClass = "";
            }
        }
        else
        {
            ddlPropertyType.ControlStyle.CssClass = "";
        }

        //Property
        //if (rfvProperty.Enabled && rfvProperty.ValidationGroup == strValidationGroup)
        //{
        //    rfvProperty.Validate();
        //    if (rfvProperty.IsValid == false)
        //    {
        //        ddlProperty.ControlStyle.CssClass = "validationError";
        //    }
        //    else
        //    {
        //        ddlProperty.ControlStyle.CssClass = "";
        //    }
        //}
        //else
        //{
        //    ddlProperty.ControlStyle.CssClass = "";
        //}

        //Financing Amount
        if (rfvLoanAmount.Enabled && rfvLoanAmount.ValidationGroup == strValidationGroup)
        {
            rfvLoanAmount.Validate();
            if (rfvLoanAmount.IsValid == false)
            {
                txtLoanAmount.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtLoanAmount.ControlStyle.CssClass = "";
            }
        }
        else
        {
            txtLoanAmount.ControlStyle.CssClass = "";
        }

        if (revLoanAmount.Enabled && revLoanAmount.ValidationGroup == strValidationGroup)
        {
            if (rfvLoanAmount.IsValid)
            {
                revLoanAmount.Validate();
                if (revLoanAmount.IsValid == false)
                {
                    txtLoanAmount.ControlStyle.CssClass = "validationError";
                }
                else
                {
                    txtLoanAmount.ControlStyle.CssClass = "";
                }
            }
        }
        else
        {
            txtLoanAmount.ControlStyle.CssClass = "";
        }

        //Loan Tenure
        //if (rfvLoanTenure.Enabled && rfvLoanTenure.ValidationGroup == strValidationGroup)
        //{
        //    rfvLoanTenure.Validate();
        //    if (rfvLoanTenure.IsValid == false)
        //    {
        //        ddlLoanTenure.ControlStyle.CssClass = "validationError";
        //    }
        //    else
        //    {
        //        ddlLoanTenure.ControlStyle.CssClass = "";
        //    }
        //}
        //else
        //{
        //    ddlLoanTenure.ControlStyle.CssClass = "";
        //}

        //Rate
        //if (rfvRate.Enabled && rfvRate.ValidationGroup == strValidationGroup)
        //{
        //    rfvRate.Validate();
        //    if (rfvRate.IsValid == false)
        //    {
        //        ddlRate.ControlStyle.CssClass = "validationError";
        //    }
        //    else
        //    {
        //        ddlRate.ControlStyle.CssClass = "";
        //    }
        //}
        //else
        //{
        //    ddlRate.ControlStyle.CssClass = "";
        //}

        ////Property Value In SGD
        //if (rfvPropertyValue.Enabled && rfvPropertyValue.ValidationGroup == strValidationGroup)
        //{
        //    rfvPropertyValue.Validate();
        //    if (rfvPropertyValue.IsValid == false)
        //    {
        //        txtPropertyValue.ControlStyle.CssClass = "validationError";
        //    }
        //    else
        //    {
        //        txtPropertyValue.ControlStyle.CssClass = "";
        //    }
        //}
        //else
        //{
        //    txtPropertyValue.ControlStyle.CssClass = "";
        //}

        //if (revPropertyValue.Enabled && revPropertyValue.ValidationGroup == strValidationGroup)
        //{
        //    if (rfvPropertyValue.IsValid)
        //    {
        //        revPropertyValue.Validate();
        //        if (revPropertyValue.IsValid == false)
        //        {
        //            txtPropertyValue.ControlStyle.CssClass = "validationError";
        //        }
        //        else
        //        {
        //            txtPropertyValue.ControlStyle.CssClass = "";
        //        }
        //    }
        //}
        //else
        //{
        //    txtPropertyValue.ControlStyle.CssClass = "";
        //}

    }

    private void ChangeCalValidationEffectServerSide(string strValidationGroup)
    {
        //Loan Amount
        if (rfvCalLoanAmount.Enabled && rfvCalLoanAmount.ValidationGroup == strValidationGroup)
        {
            rfvCalLoanAmount.Validate();
            if (rfvCalLoanAmount.IsValid == false)
            {
                txtCalLoanAmount.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtCalLoanAmount.ControlStyle.CssClass = "";
            }
        }
        else
        {
            txtCalLoanAmount.ControlStyle.CssClass = "";
        }

        if (revCalLoanAmount.Enabled && revCalLoanAmount.ValidationGroup == strValidationGroup)
        {
            if (rfvCalLoanAmount.IsValid)
            {
                revCalLoanAmount.Validate();
                if (revCalLoanAmount.IsValid == false)
                {
                    txtCalLoanAmount.ControlStyle.CssClass = "validationError";
                }
                else
                {
                    txtCalLoanAmount.ControlStyle.CssClass = "";
                }
            }
        }
        else
        {
            txtCalLoanAmount.ControlStyle.CssClass = "";
        }

        //IntrestRate
        if (rfvCalIntrestRate.Enabled && rfvCalIntrestRate.ValidationGroup == strValidationGroup)
        {
            rfvCalIntrestRate.Validate();
            if (rfvCalIntrestRate.IsValid == false)
            {
                txtCalIntrestRate.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtCalIntrestRate.ControlStyle.CssClass = "";
            }
        }
        else
        {
            txtCalIntrestRate.ControlStyle.CssClass = "";
        }

        if (revCalIntrestRate.Enabled && revCalIntrestRate.ValidationGroup == strValidationGroup)
        {
            if (rfvCalIntrestRate.IsValid)
            {
                revCalIntrestRate.Validate();
                if (revCalIntrestRate.IsValid == false)
                {
                    txtCalIntrestRate.ControlStyle.CssClass = "validationError";
                }
                else
                {
                    txtCalIntrestRate.ControlStyle.CssClass = "";
                }
            }
        }
        else
        {
            txtCalIntrestRate.ControlStyle.CssClass = "";
        }



        //LoanTenure
        if (rfvCalLoanTenure.Enabled && rfvCalLoanTenure.ValidationGroup == strValidationGroup)
        {
            rfvCalLoanTenure.Validate();
            if (rfvCalLoanTenure.IsValid == false)
            {
                txtCalLoanTenure.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtCalLoanTenure.ControlStyle.CssClass = "";
            }
        }
        else
        {
            txtCalLoanTenure.ControlStyle.CssClass = "";
        }

        if (revCalLoanTenure.Enabled && revCalIntrestRate.ValidationGroup == strValidationGroup)
        {
            if (rfvCalLoanTenure.IsValid)
            {
                revCalIntrestRate.Validate();
                if (revCalIntrestRate.IsValid == false)
                {
                    txtCalLoanTenure.ControlStyle.CssClass = "validationError";
                }
                else
                {
                    txtCalLoanTenure.ControlStyle.CssClass = "";
                }
            }
        }
        else
        {
            txtCalLoanTenure.ControlStyle.CssClass = "";
        }
    }

    private Int64 LogUserViewedHistory()
    {
        UserViewHistoryDB _userviewdb = new UserViewHistoryDB();
        return _userviewdb.LogViewedHistory("HL", Request, "Home loan mortgage property details.");
    }

    protected void btnCalculate_Click(object sender, EventArgs e)
    {
        divResult.Visible = false;
        ChangeCalValidationEffectServerSide("calculator");
        if (Page.IsValid)
        {
            float principal = Convert.ToSingle(txtCalLoanAmount.Text);
            float interest = Convert.ToSingle(txtCalIntrestRate.Text);
            //Int32 noy = Convert.ToInt32(ddlLoanTenure.Text);
            Int32 noy = Convert.ToInt32(txtCalLoanTenure.Text);


            if (principal == 0)
            {
                lblError.Text = "Please fill valued Loan Amount.";
            }
            else if (interest == 0)
            {
                lblError.Text = "Please fill valued Interest Rate.";
            }
            else if (noy == 0)
            {
                lblError.Text = "Please fill valued Length of Loan.";
            }
            else
            {
                lblError.Text = "";
            }

            if (principal != 0f && interest != 0f && noy != 0)
            {
                //var str = principal
                //var a = (str.replace(/,/, ""))
                float t_years = noy * 12;
                float t_interest = interest / 1200f;
                double t = (1.0 / (Math.Pow((1 + t_interest), t_years)));
                double payment = 0;
                if (t < 1)
                {
                    payment = ((principal * t_interest) / (1 - t));
                }

                divResult.Visible = true;
                string total = string.Empty;
                total = "S$ " + FormatThousandSeperator(payment.ToString());
                //total = String.Format("${0:f}", payment);

                string loanamount = "0";
                //if (principal >= 1000)
                //    loanamount = principal.ToString("$#,000");
                //else
                //    loanamount = principal.ToString("$#");
                loanamount = "S$ " + FormatThousandSeperator(principal.ToString());
                lblMonthlyPayment.Text = total;
                lblLoanAmount.Text = loanamount;
                lblIntrestRate.Text = interest.ToString() + "%";
                lblLoanDuration.Text = noy.ToString() + " years";

            }
        }
    }

    private string FormatThousandSeperator(string strValue)
    {
        string _retValue = strValue;
        try
        {
            Double _dValue = Convert.ToDouble(strValue);
            Double _dCValue = 1000.00d;
            if (_dValue >= _dCValue)
            {
                _retValue = _dValue.ToString("#,000.00");
            }
            else
            {
                _retValue = _dValue.ToString("#.00");
            }
        }
        catch (Exception Ex)
        {
            throw Ex;
        }


        return _retValue;
    }

    protected void btnClose_Click(object sender, EventArgs e)
    {
        txtCalLoanAmount.Text = "";
        txtCalIntrestRate.Text = "";
        txtCalLoanTenure.Text = "";
        lblError.Text = "";
        divResult.Visible = false;
        mpeCalculator.Hide();
    }

    private void GetCurrentBankList()
    {
        MyDatabase _mydb = new MyDatabase();
        DataTable _dtBankList = new DataTable("tblBankList");
        _dtBankList = _mydb.GetDataTable("Select BankValue, BankName from tblHLBankList Where Status = 1;");
        if (_dtBankList != null && _dtBankList.Rows.Count > 0)
        {
            ddlYourCurrentBank.Items.Clear();
            ddlYourCurrentBank.Items.Add(new ListItem("Select", "-1"));
            for (int i = 0; i < _dtBankList.Rows.Count; i++)
            {
                ddlYourCurrentBank.Items.Add(new ListItem(_dtBankList.Rows[i]["BankValue"].ToString(), _dtBankList.Rows[i]["BankName"].ToString()));
            }

        }
        else
        {
            ddlYourCurrentBank.Items.Add(new ListItem("Select", "-1"));
        }
    }

}
